import React from 'react';
import ReactDOM from 'react-dom';
import promiseMiddleware from 'redux-promise';
import {createStore, combineReducers, applyMiddleware} from 'redux';
import fetch from 'isomorphic-fetch';
import fetchReducer from './reducers/fetchReducer';
const store = createStore(fetchReducer, applyMiddleware(promiseMiddleware));
class SampleCom extends React.Component {
	fetchData() {
		// 开始取得数据，这个是同步处理
		this.props.dispatch({
			type: "FETCH_DATA_START"
		});
		// 取得数据
		this.props.dispatch({
			type: "FETCH_DATA_FINISH",
			payload: fetch("/data_api/users/").then(function(response)
			{return response.json()})
		});
	}
	render() {
		let list = [];
		if(this.props.data.list) {
			list = this.props.data.list.map(function(item, idx){
				return <li key={idx}>{item.name} {item.age}</li>;
			})
		}
		return (
			<div>
				{this.props.data.status}<br/>
				<ul>
				{list}
				</ul>
				<button onClick={this.fetchData.bind(this)}>请求ajax</button>
			</div>
		)
	}
}
function render() {
	ReactDOM.render(
		<SampleCom data={store.getState()} dispatch={(arg)=>{store.dispatch(arg)}} />,
		document.getElementById("example")
	);
}
render();
store.subscribe(render);
